aregmi.net
Resume

PowerShell Cheat sheet

Navigation & File System

Get-Location                    # Print working directory (alias: pwd)
Set-Location C:\path            # Change directory (alias: cd)
Set-Location ~                  # Home directory
Set-Location -                  # Previous directory
Push-Location .\subdir          # Push onto directory stack
Pop-Location                    # Pop back to previous

Get-ChildItem                   # List files (alias: ls, dir, gci)
Get-ChildItem -Force            # Include hidden files
Get-ChildItem -Recurse *.py     # Recursive search by pattern
Get-ChildItem | Sort-Object Length -Descending  # Sort by size

File Operations

Copy-Item file.txt copy.txt                 # Copy file
Copy-Item -Recurse dir\ dir_copy\           # Copy directory
Move-Item old.txt new.txt                   # Rename/move
Remove-Item file.txt                        # Delete file
Remove-Item -Recurse -Force dir\            # Delete directory
New-Item -ItemType File file.txt            # Create file
New-Item -ItemType Directory mydir          # Create directory
New-Item -ItemType Directory -Force a\b\c   # Create nested dirs
Test-Path file.txt                          # Check if exists → True/False

Viewing & Reading Files

Get-Content file.txt                        # Read entire file (alias: cat, gc, type)
Get-Content file.txt -First 20              # First 20 lines (like head)
Get-Content file.txt -Last 20               # Last 20 lines (like tail)
Get-Content file.txt -Tail 10 -Wait         # Follow file (like tail -f)
Get-Content file.txt | Measure-Object -Line # Count lines
Get-Content file.txt | Measure-Object -Word # Count words

Set-Content file.txt "hello"                # Write to file (overwrite)
Add-Content file.txt "more"                 # Append to file
"hello" | Out-File file.txt                 # Write with encoding control
"more" | Out-File file.txt -Append          # Append

Searching

# Find files
Get-ChildItem -Recurse -Filter *.py             # Find by pattern
Get-ChildItem -Recurse | Where-Object { $_.Length -gt 1MB }  # By size
Get-ChildItem -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }  # Recent

# Search in file contents
Select-String -Pattern "text" -Path file.txt          # Grep equivalent
Select-String -Pattern "text" -Path *.py -Recurse     # Recursive search
Select-String -Pattern "text" -Path file.txt -CaseSensitive
Select-String -Pattern "foo|bar" -Path file.txt       # Regex OR
Select-String -Pattern "text" -Path file.txt -NotMatch # Invert match
Select-String -Pattern "text" -Path *.py -Recurse | Select-Object FileName, LineNumber, Line

Text Processing & String Operations

# String methods
$s = "Hello World"
$s.Length                       # 11
$s.ToLower()                    # hello world
$s.ToUpper()                    # HELLO WORLD
$s.Trim()                       # Remove whitespace both ends
$s.TrimStart()                  # Remove leading whitespace
$s.TrimEnd()                    # Remove trailing whitespace
$s.Substring(0, 5)              # Hello
$s.Replace("World", "PS")       # Hello PS
$s.Split(" ")                   # @('Hello', 'World')
$s.Contains("World")            # True
$s.StartsWith("He")             # True
$s.EndsWith("ld")               # True
$s.IndexOf("World")             # 6
$s.PadLeft(20, '-')             # ---------Hello World
$s.PadRight(20, '-')            # Hello World---------
$s.Insert(5, ",")               # Hello, World

# String interpolation
$name = "World"
"Hello $name"                   # Hello World
"Result: $($arr.Count)"        # Expression in string
'No $expansion'                 # Single quotes = literal
"Price: `$5"                    # Backtick to escape $

# Regex
"abc123" -match '\d+'           # True, $Matches[0] = "123"
"abc123" -replace '\d+', 'NUM'  # abcNUM
[regex]::Matches("a1b2c3", '\d') | ForEach-Object { $_.Value }  # 1, 2, 3

# Here-strings (multiline)
$text = @"
Line 1
Line 2 with $name
"@

Objects & Pipeline

# PowerShell pipes OBJECTS, not text
Get-Process | Select-Object Name, CPU, Id           # Pick properties
Get-Process | Where-Object { $_.CPU -gt 10 }        # Filter
Get-Process | Sort-Object CPU -Descending            # Sort
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5  # Top 5
Get-Process | Group-Object ProcessName               # Group by
Get-Process | Measure-Object WorkingSet -Sum -Average # Stats
Get-Process | ForEach-Object { $_.Name.ToUpper() }   # Transform each

# Useful pipeline patterns
1..10 | Where-Object { $_ % 2 -eq 0 }               # Even numbers: 2,4,6,8,10
1..10 | ForEach-Object { $_ * $_ }                   # Squares
"a","b","c" | ForEach-Object { $_.ToUpper() }        # A, B, C

Variables & Data Types

$x = 42                        # Integer
$s = "hello"                   # String
$arr = @(1, 2, 3)              # Array
$hash = @{ key = "value"; num = 42 }  # Hashtable (dictionary)
[int]$x = "42"                 # Type casting
$null                          # Null value

# Array operations
$arr = @(1, 2, 3, 4, 5)
$arr[0]                        # First element → 1
$arr[-1]                       # Last element → 5
$arr[1..3]                     # Slice → 2, 3, 4
$arr += 6                      # Append (creates new array)
$arr.Count                     # Length → 6
$arr -contains 3               # True
$arr | Where-Object { $_ -gt 3 }  # Filter → 4, 5, 6
1..10                          # Range → 1,2,3,...,10

# Hashtable operations
$hash = @{ name = "Alice"; age = 30 }
$hash["name"]                  # Access → Alice
$hash.name                     # Dot notation → Alice
$hash["city"] = "NYC"          # Add/update key
$hash.Remove("age")            # Remove key
$hash.Keys                     # All keys
$hash.Values                   # All values
$hash.ContainsKey("name")      # True
$hash.Count                    # Number of entries

Conditionals

# if/elseif/else
if ($x -eq 5) {
    "five"
} elseif ($x -gt 5) {
    "more"
} else {
    "less"
}

# Comparison operators
# -eq  -ne  -lt  -le  -gt  -ge        (numeric/string)
# -ceq -cne -clt ...                   (case-sensitive)
# -like  -notlike                       (wildcard: * ?)
# -match -notmatch                      (regex)
# -contains -notcontains                (collection contains value)
# -in -notin                            (value in collection)
# -is -isnot                            (type check)

# Examples
"hello" -like "hel*"          # True (wildcard)
"hello" -match "^h.*o$"       # True (regex)
@(1,2,3) -contains 2          # True
2 -in @(1,2,3)                # True
$x -is [int]                  # Type check

# Ternary (PS 7+)
$result = $x -gt 0 ? "positive" : "non-positive"

# Switch
switch ($color) {
    "red"   { "stop" }
    "green" { "go" }
    default { "unknown" }
}

Loops

# ForEach-Object (pipeline)
1..5 | ForEach-Object { $_ * 2 }

# foreach statement
foreach ($item in $collection) {
    Write-Output $item
}

# for loop
for ($i = 0; $i -lt 10; $i++) {
    Write-Output $i
}

# while loop
while ($x -lt 10) {
    $x++
}

# do-while / do-until
do { $x++ } while ($x -lt 10)
do { $x++ } until ($x -ge 10)

Functions

function Get-Greeting {
    param(
        [string]$Name = "World",
        [int]$Times = 1
    )
    for ($i = 0; $i -lt $Times; $i++) {
        "Hello, $Name"
    }
}
Get-Greeting -Name "Alice" -Times 2

# Simple function
function Add-Numbers($a, $b) { $a + $b }
Add-Numbers 3 4    # → 7

Error Handling

try {
    Get-Content "missing.txt" -ErrorAction Stop
} catch {
    Write-Error "Failed: $_"
    $_.Exception.Message        # Error message
} finally {
    # Always runs
}

# Error action preferences
$ErrorActionPreference = "Stop"           # Make all errors terminating
Get-Content file.txt -ErrorAction SilentlyContinue  # Suppress errors

Process Management

Get-Process                                # List all processes
Get-Process -Name python                   # Find by name
Get-Process | Where-Object { $_.CPU -gt 100 }
Stop-Process -Id 1234                      # Kill by PID
Stop-Process -Name notepad                 # Kill by name
Start-Process notepad                      # Launch process
Start-Process cmd -ArgumentList "/c dir"   # With arguments
Start-Job { Get-ChildItem -Recurse }       # Background job
Get-Job                                    # List jobs
Receive-Job -Id 1                          # Get job output

Networking

Invoke-WebRequest -Uri $url                              # Fetch URL (alias: curl, wget)
Invoke-WebRequest -Uri $url -OutFile file.zip            # Download file
Invoke-RestMethod -Uri $url                              # Fetch + auto-parse JSON
Invoke-RestMethod -Uri $url -Method Post -Body ($data | ConvertTo-Json) -ContentType "application/json"

Test-Connection google.com -Count 4                      # Ping
Test-NetConnection localhost -Port 8080                  # Check port
Resolve-DnsName google.com                               # DNS lookup

JSON & CSV

# JSON
$obj = '{"name":"Alice","age":30}' | ConvertFrom-Json
$obj.name                                   # Alice
$obj | ConvertTo-Json                        # Back to JSON string
Get-Content data.json | ConvertFrom-Json     # Read JSON file

# CSV
$data = Import-Csv data.csv                  # Read CSV → objects
$data | Export-Csv output.csv -NoTypeInformation  # Write CSV
$data | Where-Object { $_.Age -gt 25 }       # Filter rows
$data | Select-Object Name, Age              # Pick columns
$data | Sort-Object Age                      # Sort
$data | Group-Object City                    # Group
$data | Measure-Object Age -Average -Maximum # Stats

Disk & System

Get-PSDrive                                 # List drives
Get-Volume                                  # Disk info
Get-ChildItem -Recurse | Measure-Object -Property Length -Sum   # Dir size
Get-ComputerInfo                            # System info
Get-CimInstance Win32_OperatingSystem        # OS details
$PSVersionTable                             # PowerShell version
[Environment]::OSVersion                    # OS version
Get-Uptime                                  # System uptime (PS 7+)

Environment Variables

$env:PATH                                   # Read PATH
$env:MY_VAR = "value"                       # Set for session
[Environment]::SetEnvironmentVariable("MY_VAR", "value", "User")  # Persistent
$env:PATH -split ';'                        # List PATH entries

Archives

Compress-Archive -Path dir\ -DestinationPath archive.zip
Expand-Archive -Path archive.zip -DestinationPath .\output
Compress-Archive -Path *.log -DestinationPath logs.zip

Modules & Help

Get-Command *process*                       # Find commands by name
Get-Help Get-Process -Full                   # Detailed help
Get-Help Get-Process -Examples               # Just examples
Get-Member -InputObject $obj                 # Inspect object properties/methods
$obj | Get-Member                            # Same via pipeline
Get-Module -ListAvailable                    # Installed modules
Install-Module ModuleName                    # Install from PSGallery
Import-Module ModuleName                     # Load module

Useful One-Liners

# Count files in directory
(Get-ChildItem -Recurse -File).Count

# Find largest files
Get-ChildItem -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 Name, @{N='MB';E={[math]::Round($_.Length/1MB,2)}}

# Replace in all files
Get-ChildItem -Recurse -Filter *.py | ForEach-Object { (Get-Content $_) -replace 'old','new' | Set-Content $_ }

# Monitor log file
Get-Content app.log -Tail 10 -Wait | Where-Object { $_ -match "ERROR" }

# Kill process on port
Get-NetTCPConnection -LocalPort 8080 | ForEach-Object { Stop-Process -Id $_.OwningProcess }

# Quick HTTP server (Python)
python -m http.server 8000

# Generate random string
-join ((65..90) + (97..122) | Get-Random -Count 16 | ForEach-Object { [char]$_ })

# Measure command execution time
Measure-Command { Get-ChildItem -Recurse }

# Clipboard operations
Get-Clipboard                               # Read clipboard
Set-Clipboard "text"                        # Write to clipboard
Get-Process | Out-String | Set-Clipboard    # Copy output

Quick Reference

Need Command
Find a file Get-ChildItem -Recurse -Filter "pattern"
Search in files Select-String -Pattern "text" -Recurse
Replace in file (Get-Content f) -replace 'old','new' | Set-Content f
Count lines (Get-Content file).Count
Sort + dedupe Get-Content file | Sort-Object -Unique
Download file Invoke-WebRequest -Uri $url -OutFile f
Parse JSON Get-Content f.json | ConvertFrom-Json
Parse CSV Import-Csv data.csv
Check port Test-NetConnection localhost -Port 8080
Disk usage Get-ChildItem | Select-Object Name, Length
Object properties $obj | Get-Member
Run as admin Start-Process pwsh -Verb RunAs